package com.sun.newapp;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;


/**
 * Created by sunjj on 2019/11/1.
 */
public class ScanActivity extends Activity implements QRCodeView.Delegate{
    @ViewInject(R.id.zxingview)
    ZXingView zXingView;
    private boolean isLight;
    @ViewInject(R.id.ll_content)
    LinearLayout ll_content;
    @ViewInject(R.id.tv_content)
    TextView tv_content;
    @ViewInject(R.id.iv_deng)
    ImageView iv_deng;
    @ViewInject(R.id.tv_title)
    TextView tv_title;
    private int  camera;
    private float scan;
    private HttpUtils httpUtils;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private double latitude;
    private double longitude;
    private double altitude;

    //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
    @OnClick({R.id.iv_deng,R.id.iv_camera,R.id.iv_back})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
//                setResult(0);
                finish();
                break;
            case R.id.iv_deng:
                if(!isLight){
                    zXingView.openFlashlight();
                    iv_deng.setImageResource(R.mipmap.icon_deng_an);
                }else {
                    zXingView.closeFlashlight();
                    iv_deng.setImageResource(R.mipmap.icon_deng_liang);
                }
                isLight=!isLight;
                break;
            case R.id.iv_camera:
                zXingView.stopCamera();
                if(camera==Camera.CameraInfo.CAMERA_FACING_BACK){
                    camera=Camera.CameraInfo.CAMERA_FACING_FRONT;
                }else {
                    camera=Camera.CameraInfo.CAMERA_FACING_BACK;
                }
                SharedPreferencesUtils.setInt(this,"camera",camera);
                zXingView.startCamera(camera);
                zXingView.startSpotAndShowRect();
                break;
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        ViewUtils.inject(this);
        zXingView.setDelegate(this);
        zXingView.setType(BarcodeType.HIGH_FREQUENCY, null);
        httpUtils = new HttpUtils();
        scan = getIntent().getFloatExtra("scan",0);
        if(scan>0){
            tv_title.setText("连续扫码");
        }else {
            tv_title.setText("单次扫码");
        }
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();

        option.setIsNeedAddress(true);
//可选，是否需要地址信息，默认为不需要，即参数为false
//如果开发者需要获得当前点的地址信息，此处必须为true
        option.setIsNeedAltitude(true);
        option.setNeedNewVersionRgc(true);
//可选，设置是否需要最新版本的地址信息。默认需要，即参数为true

        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        camera=SharedPreferencesUtils.getInt(this,"camera",Camera.CameraInfo.CAMERA_FACING_BACK);
        zXingView.startCamera(camera); // 打开后置摄像头开始预览，但是并未开始识别
        zXingView.startSpotAndShowRect(); // 显示扫描框，并且延迟0.5秒后开始识别
        Log.e("TAG","onStart");
    }

    @Override
    protected void onStop() {
        Log.e("TAG","onStop");
        zXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

//            String addr = location.getAddrStr();    //获取详细地址信息
//            String country = location.getCountry();    //获取国家
//            String province = location.getProvince();    //获取省份
//            String city = location.getCity();    //获取城市
//            String district = location.getDistrict();    //获取区县
//            String street = location.getStreet();    //获取街道信息
//            String adcode = location.getAdCode();    //获取adcode
//            String town = location.getTown();    //获取乡镇信息
            latitude=location.getLatitude();
            longitude=location.getLongitude();
            altitude=location.getAltitude();
            if(latitude+"".length()>5){
                    altitude=-1;
            }
        }
    }
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        Log.e("TAG",result);

//        ll_content.setVisibility(View.VISIBLE);
        //
        String url=SharedPreferencesUtils.getString(this,"url","");
        RequestParams params = new RequestParams();
        params.addBodyParameter("str",result);
        params.addBodyParameter("x",latitude+"");
        params.addBodyParameter("y",longitude+"");
        params.addBodyParameter("z",altitude+"");
        httpUtils.send(HttpRequest.HttpMethod.POST, "http://"+url+"/Accept/?IMEI="+DeviceIdUtils.getLocalDeviceId(this),params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
//                Log.e("TAG", responseInfo.result);
//                tv_content.setText(responseInfo.result);
                Intent intent=new Intent();
                intent.putExtra("data",responseInfo.result);
                intent.putExtra("scan",scan);
                setResult(1,intent);
                finish();
            }
            @Override
            public void onFailure(HttpException e, String s) {
                Log.e("TAGe", s);
            }
        });
//        if(scan>0){
//            TimerTask task = new TimerTask() {
//                @Override
//                public void run() {
//                    //要执行的操作
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            ll_content.setVisibility(View.GONE);
//                            zXingView.startSpotAndShowRect();
//                        }
//                    });
//                }
//            };
//            Timer timer = new Timer();
//            timer.schedule(task, (long) (scan*1000));//2秒后执行TimeTask的run方法
//        }
//        Toast.makeText(this,result,Toast.LENGTH_SHORT);
//        Intent intent=new Intent();
//        intent.putExtra("data",result);
//        setResult(LOGIN,intent);
//        finish();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e("TAG", "打开相机出错");
    }

}
